package com.youdianstar.app.ui.account


import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.text.Html
import android.view.KeyEvent
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.credentials.CredentialManager
import androidx.credentials.CustomCredential
import androidx.credentials.GetCredentialRequest
import androidx.credentials.GetCredentialResponse
import androidx.lifecycle.Observer
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.google.android.libraries.identity.googleid.GetSignInWithGoogleOption
import com.google.android.libraries.identity.googleid.GoogleIdTokenCredential
import com.google.android.libraries.identity.googleid.GoogleIdTokenParsingException

import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.databinding.ActivityLoginBinding
import com.youdianstar.app.entity.AccountLoginReq
import com.youdianstar.app.entity.MobileLoginResponse
import com.youdianstar.app.entity.PhoneCurrent
import com.youdianstar.app.entity.UserCenterResponse
import com.youdianstar.app.ui.MainActivity
import com.youdianstar.app.ui.web.WebActivity
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.util.biometric.BiometricPopUtil
import com.youdianstar.app.util.biometric.CryptographyHelper
import com.youdianstar.app.util.biometric.IBiometricPopListener

import com.youdianstar.app.common.*
import com.youdianstar.app.common.HTTP_BRS_URL
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.entity.Account
import com.youdianstar.app.common.entity.UserInfo
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.util.LanguageConfig
import com.youdianstar.app.common.util.StrUtil
import com.youdianstar.app.common.widget.ClickURLSpan
import com.youdianstar.app.common.ex.getViewColor
import com.youdianstar.app.common.entity.BrandEntity
import com.youdianstar.app.common.entity.BrandSwitch
import com.youdianstar.app.common.util.LogUtil
import com.youdianstar.app.common.auko.startActivity
import com.youdianstar.app.common.entity.ConfigItem
import com.youdianstar.app.common.util.ScreenUtil
import com.youdianstar.app.entity.CountryData

import com.gyf.immersionbar.ImmersionBar
import com.youdianstar.app.util.JwtParserUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.util.*
import javax.crypto.Cipher


class LoginActivity : BaseActivity<ActivityLoginBinding, LoginViewModel>() {

    override fun layoutId(): Int = R.layout.activity_login

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): LoginViewModel {
        val model: LoginViewModel by viewModel()
        return model
    }

    private val mHandler = Handler(Looper.myLooper()!!)
    private lateinit var phoneCodeLauncher: ActivityResultLauncher<Intent>
    private var countryCode: String = ""

    //Google 登录
    private val scope = CoroutineScope(Dispatchers.Main)
    private var credentialManager : CredentialManager? = null
    private var mGoogleRequest: GetCredentialRequest?=null
    // Biometric 指纹数据
    private val bioHelper : CryptographyHelper = CryptographyHelper.getInstance()
    private var wrapperCache : CryptographyHelper.CipherTextWrapper? =null

    //标记页面设置: 0-选择 1-手机 2-邮箱
    private var pageTag = 0
    //上次登录Tag
    private var viewFocusTag = false
    //1 手机 2 邮件 3 Google 4.Token
    private var typeTag = 0

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus && !viewFocusTag){
            viewFocusTag = true
            DataAppManager.instance.getAccount()?.let { ac ->
                when(ac.type){
                    1->{
                        setRecentLayoutTag(mBinding.clSelectPhone.id)
                        mBinding.edtPhone.setText(ac.phone)
                    }
                    // 邮箱和Google登录已注释
                    /*
                    2->{
                        setRecentLayoutTag(mBinding.clSelectEmail.id)
                        mBinding.edtEmail.setText(ac.email)
                    }
                    3->{
                        setRecentLayoutTag(mBinding.clSelectGoogle.id)
                    }
                    */
                    else -> mBinding.tagContainer.visibility = View.INVISIBLE
                }
            }
        }
    }

    override fun initData() {
        super.initData()
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .titleBarMarginTop(mBinding.llHeadTop)
            .init()
        val agreeContent = Html.fromHtml(getString(R.string.login_agree_Html))
        mBinding.tvAgreementContent.text = agreeContent
        ClickURLSpan.textUnderline(mBinding.tvAgreementContent,R.color.color_39404D) {
            val langParam = getAgreementLangParam()
            if (it == TERM_URL) {
                val termsUrl = "${HTTP_BRS_URL}/sw/app/agreement/user.html?lang=$langParam"
                startActivity<WebActivity>(Extra.IT_DATA to termsUrl, Extra.IT_NOTIFY to getString(R.string.login_termOfUse))
            } else if (it == PRIVACY_URL) {
                val policyUrl = "${HTTP_BRS_URL}/sw/app/agreement/privacy.html?lang=$langParam"
                startActivity<WebActivity>(Extra.IT_DATA to policyUrl, Extra.IT_NOTIFY to getString(R.string.login_privacyPolice))
            }
        }
        phoneCodeLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            result.data?.let { codeData ->
                codeData.getStringExtra(Extra.IT_CODE)?.let { code ->
                    setCountryCode(code)
                }
            }
        }
        /*数据初始化 - 设置默认国家为越南*/
        countryCode = DataAppManager.instance.getPhoneCode()
        if(StrUtil.isEmpty(countryCode) || countryCode == "1"){
            // 设置默认国家为越南(84)
            setCountryCode(CountryData.DEFAULT_COUNTRY.code.toString())
            DataAppManager.instance.savePhoneCode(CountryData.DEFAULT_COUNTRY.code.toString())
        }else{
            setCountryCode(countryCode)
        }

        //显示指纹 - 已注释
        // setBiometricLayout()
        //Google 初始化
        initGoogleLogin()

        if (!DataAppManager.instance.isRequestConfig){
            // 系统配置接口已屏蔽
            // showLoadingDialog()
            // mViewModel.getSystemConfig()
        }
        setMethodLayout()
    }

    override fun onPause() {
        super.onPause()
        mViewModel.dismissAgreeBur()
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        //系统配置接口 - 已屏蔽
        /*
        mViewModel.configResultLiveData.observe(this,object : BaseApiResultObserver<List<ConfigItem>>(){
            override fun onDataResult(data: List<ConfigItem>?) {
                super.onDataResult(data)
                dismissDialog()
                data?.let {
                    DataAppManager.instance.isRequestConfig = true
                    DataAppManager.instance.saveConfig(it)
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
            }
        })
        */

        // IP获取国家代码 - 已注释，使用本地默认数据
        /*
        mViewModel.phoneCodeCurrentData.observe(this, object : BaseApiResultObserver<PhoneCurrent>() {
            override fun onDataResult(data: PhoneCurrent?) {
                super.onDataResult(data)
                data?.let { pc ->
                    val code = pc.code.toString()
                    setCountryCode(code)//IP 获取 默认国家地区码
                    DataAppManager.instance.savePhoneCode(code)
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                toastShow(e)
            }
        })
        */

        mViewModel.burCountEvent.observe(this, Observer {
            if (it >= 5) {
                mBinding.clAgreeBubo.visibility = View.INVISIBLE
            } else {
                if (mBinding.clAgreeBubo.isInvisible)
                    mBinding.clAgreeBubo.visibility = View.VISIBLE
            }
        })

        mViewModel.phoneCountEvent.observe(this, Observer { count ->
            if (count == -1L) {
                mBinding.phoneSendOtp.isEnabled = true
                mBinding.phoneSendOtp.text = getString(R.string.login_get)
            } else {
                var time = "$count"
                if (time.length == 1) {
                    time = "0$count"
                }
                mBinding.phoneSendOtp.isEnabled = false
                mBinding.phoneSendOtp.text = time + "s"
            }
        })

        mViewModel.emailCountEvent.observe(this, Observer { count ->
            if (count == -1L) {
                mBinding.emailSendOtp.isEnabled = true
                mBinding.emailSendOtp.text = getString(R.string.login_get)
            } else {
                var time = "$count"
                if (time.length == 1) {
                    time = "0$count"
                }
                mBinding.emailSendOtp.isEnabled = false
                mBinding.emailSendOtp.text = time + "s" //String.format(getString(R.string.Login_ResendIn), time)
            }
        })

        mViewModel.otpPhoneResultData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                dismissDialog()
                mViewModel.onPhoneOtpSuccess()
                mViewModel.downCountPhone()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
                if (code == HttpCode.CODE_OTP_UNABLE || code == HttpCode.CODE_OTP_OVER) {
                    mBinding.phoneSendOtp.isClickable = false
                    mBinding.phoneSendOtp.setTextColor(getViewColor(this@LoginActivity,R.color.text_hint_input))
                }
            }
        })

        mViewModel.otpEmailResultData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                dismissDialog()
                mViewModel.onEmailOtpSuccess()
                mViewModel.downCountEmail()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
                if (code == HttpCode.CODE_OTP_UNABLE || code == HttpCode.CODE_OTP_OVER) {
                    mBinding.emailSendOtp.isClickable = false
                    mBinding.emailSendOtp.setTextColor(getViewColor(this@LoginActivity,R.color.text_hint_input))
                }
            }
        })

        mViewModel.loginResultLiveData.observe(this, object : BaseApiResultObserver<MobileLoginResponse>(false) {
            override fun onDataResult(data: MobileLoginResponse?) {
                super.onDataResult(data)
                dismissDialog()
                data?.let { loginResponse ->
                    // 创建UserInfo对象来保持兼容性
                    val userInfo = UserInfo(
                        token = loginResponse.userId.toString(), // 使用userId作为token，与前端逻辑一致
                        id = loginResponse.userId,
                        code = null,
                        phone = loginResponse.mobile,
                        email = null,
                        nickname = loginResponse.nickName,
                        realName = loginResponse.realName,
                        abb = loginResponse.language,
                        icon = loginResponse.avatar,
                        birthday = null,
                        sex = 0,
                        google = false,
                        receiptEmail = null,
                        deposit = false,
                        inviteId = null,
                        inviteCode = "",
                        platformId = 0,
                        uid = loginResponse.userId,
                        type = 1,
                        source = 1,
                        isNewUser = false,
                        isBranch = false
                    )
                    DataAppManager.instance.saveUser(userInfo)
                    //记录账户缓存
                    val updateAccount = Account(type = typeTag, id = loginResponse.userId, code = null, phone = loginResponse.mobile, email = null)
                    DataAppManager.instance.saveAccount(updateAccount)
                    //默认切换平台 : 1 - 接口已屏蔽，不再调用
                    // mViewModel.switchBrand(BrandSwitch(1),false)
                    
                    // 设置默认平台信息（避免接口调用）
                    DataAppManager.instance.getUser()?.platformId = 1
                    DataAppManager.instance.getUser()?.uid = loginResponse.userId
                    DataAppManager.instance.saveCacheUser()
                    DataAppManager.instance.isRequestConfig = false
                    
                    // 直接跳转到主页（不再等待平台切换接口响应）
                    startActivity<MainActivity>()
                    
                    // 登录成功后获取用户中心完整信息
                    mViewModel.getAccount()
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })

        // 观察用户中心数据更新
        mViewModel.userCenterResultLiveData.observe(this, object : BaseApiResultObserver<UserCenterResponse>(false) {
            override fun onDataResult(data: UserCenterResponse?) {
                super.onDataResult(data)
                data?.let { userCenterResponse ->
                    // 更新用户信息
                    DataAppManager.instance.getUser()?.let { local ->
                        val netUser = userCenterResponse.user
                        local.code = netUser.id
                        local.phone = netUser.mobile
                        local.email = netUser.email
                        local.icon = netUser.avatar
                        local.nickname = netUser.nickName
                        local.birthday = netUser.birthday
                        local.sex = netUser.sex
                        local.google = false
                        local.isBranch = false
                        DataAppManager.instance.saveCacheUser()
                    }
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                // 即使获取用户中心信息失败，也继续跳转到主页
            }
        })

        mViewModel.branchSwitchLiveData.observe(this,object: BaseApiResultObserver<BrandEntity>(){
            override fun onDataResult(data: BrandEntity?) {
                super.onDataResult(data)
                dismissDialog()
                DataAppManager.instance.isRequestConfig = false
                data?.let {
                    DataAppManager.instance.getUser()?.platformId = it.id
                    DataAppManager.instance.getUser()?.uid = it.uid?:0
                    DataAppManager.instance.saveCacheUser()
                }
                startActivity<MainActivity>()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
                startActivity<MainActivity>()
            }
        })
    }

    override fun initClickEvent() {
        mBinding.loginBoxAgree.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                if (mBinding.clAgreeBubo.isVisible)
                    mViewModel.dismissAgreeBur()
            }
        }

        mBinding.ivBackLogin.setThrottleListener {
            setMethodLayout()
        }

        mBinding.clSelectPhone.setThrottleListener {
            if (!mBinding.loginBoxAgree.isChecked) {
                mViewModel.showAgreeBurLayout()
                return@setThrottleListener
            }
            showLoginPhoneLayout()
        }

        // 邮箱登录 - 已注释
        /*
        mBinding.clSelectEmail.setThrottleListener {
            if (!mBinding.loginBoxAgree.isChecked) {
                mViewModel.showAgreeBurLayout()
                return@setThrottleListener
            }
            showLoginEmailLayout()
        }
        */

        // Google登录 - 已注释
        /*
        mBinding.clSelectGoogle.setThrottleListener {
            if (!mBinding.loginBoxAgree.isChecked) {
                mViewModel.showAgreeBurLayout()
                return@setThrottleListener
            }
            checkGoogleLogin()
        }
        */

        // 指纹登录 - 已注释
        /*
        mBinding.ivTouchId.setThrottleListener {
            if (!mBinding.loginBoxAgree.isChecked) {
                mViewModel.showAgreeBurLayout()
                return@setThrottleListener
            }
            showBiometricAuth() //显示指纹认证
        }
        */

        mBinding.tvPhoneCode.setThrottleListener {
            Intent(this@LoginActivity, PhoneCodeActivity::class.java).run {
                phoneCodeLauncher.launch(this)
            }
        }

        mBinding.phoneSendOtp.setThrottleListener {
            //点击发送判断
            if (StrUtil.isEmpty(countryCode)) {
                toastShow(getString(R.string.toast_areaCode))
                return@setThrottleListener
            }
            val phoneFiled = mBinding.edtPhone.text.toString()
            if (StrUtil.isEmpty(phoneFiled)) {
                toastShow(getString(R.string.toast_requiredPhone))
                return@setThrottleListener
            }
            if (!StrUtil.isEmpty(phoneFiled) && phoneFiled.length < 8) {
                toastShow(getString(R.string.toast_validPhone))
                return@setThrottleListener
            }

            showLoadingDialog()
            getOTPAction(true, accountStr = phoneFiled)
        }

        mBinding.emailSendOtp.setThrottleListener {
            //点击发送判断
            val emailFiled = mBinding.edtEmail.text.toString()
            if (StrUtil.isEmpty(emailFiled)) {
                toastShow(getString(R.string.toast_requiredEmail))
                return@setThrottleListener
            }
            if (!StrUtil.emailFormat(emailFiled)) {
                toastShow(getString(R.string.toast_validEmail))
                return@setThrottleListener
            }

            showLoadingDialog()
            getOTPAction(false, emailFiled)
        }

        mBinding.btnPhoneAction.setThrottleListener {
            if (StrUtil.isEmpty(countryCode)) {
                toastShow(getString(R.string.toast_areaCode))
                return@setThrottleListener
            }
            val phoneFiled = mBinding.edtPhone.text.toString()
            if (StrUtil.isEmpty(phoneFiled)) {
                toastShow(getString(R.string.toast_requiredPhone))
                return@setThrottleListener
            }
            if (!StrUtil.isEmpty(phoneFiled) && phoneFiled.length < 8) {
                toastShow(getString(R.string.toast_validPhone))
                return@setThrottleListener
            }

            val otpPhoneFiled = mBinding.edtOtpPhone.text.toString()
            if (StrUtil.isEmpty(otpPhoneFiled)){
                toastShow(getString(R.string.toast_requiredCode))
                return@setThrottleListener
            }
            if (otpPhoneFiled.length < 3){
                toastShow(getString(R.string.toast_validCode))
                return@setThrottleListener
            }

            showLoadingDialog("")
            typeTag = 1
            mViewModel.loginAccount(countryCode, phoneFiled, otpPhoneFiled)
            hideSoftKeyboard(this)
        }

        mBinding.btnEmailAction.setThrottleListener {
            val emailFiled = mBinding.edtEmail.text.toString()
            if (StrUtil.isEmpty(emailFiled)) {
                toastShow(getString(R.string.toast_requiredEmail))
                return@setThrottleListener
            }
            if (!StrUtil.emailFormat(emailFiled)) {
                toastShow(getString(R.string.toast_validEmail))
                return@setThrottleListener
            }
            val otpEmailFiled = mBinding.edtOtpEmail.text.toString()
            if (StrUtil.isEmpty(otpEmailFiled)){
                toastShow(getString(R.string.toast_requiredCode))
                return@setThrottleListener
            }
            if (otpEmailFiled.length < 3){
                toastShow(getString(R.string.toast_validCode))
                return@setThrottleListener
            }

            showLoadingDialog("")
            typeTag = 2
            // TODO: 邮箱登录功能需要新的API接口支持
            // mViewModel.loginAccount(AccountLoginReq(
            //     code = null, phone = null, email = emailFiled, msgCode = otpEmailFiled,
            //     loginType = 6, source = 1))
            hideSoftKeyboard(this)
        }
    }


    /**
     * 设置标签位置
     * @param tagId 标签布局id
     */
    private fun setRecentLayoutTag(tagId:Int){
        val setCont = ConstraintSet()
        setCont.clone(mBinding.methodContainer)
        setCont.clear(mBinding.tagContainer.id, ConstraintSet.END)
        setCont.clear(mBinding.tagContainer.id, ConstraintSet.BOTTOM)
        setCont.connect(mBinding.tagContainer.id, ConstraintSet.END, tagId, ConstraintSet.END, ScreenUtil.dp2px(this@LoginActivity,30F).toInt())
        setCont.connect(mBinding.tagContainer.id, ConstraintSet.BOTTOM, tagId, ConstraintSet.BOTTOM,ScreenUtil.dp2px(this@LoginActivity,38F).toInt())
        setCont.applyTo(mBinding.methodContainer)
        mBinding.tagContainer.visibility = View.VISIBLE
    }


    /*****************************************手机+邮箱********************************************/

    private fun setMethodLayout(){
        pageTag = 0
        mBinding.ivBackLogin.visibility = View.INVISIBLE
        mBinding.emailContainer.visibility = View.GONE
        mBinding.phoneContainer.visibility = View.GONE
        mBinding.methodContainer.visibility = View.VISIBLE
    }

    private fun showLoginPhoneLayout(){
        pageTag = 1
        mBinding.ivBackLogin.visibility = View.VISIBLE
        mBinding.methodContainer.visibility = View.GONE
        mBinding.emailContainer.visibility = View.GONE
        mBinding.phoneContainer.visibility = View.VISIBLE
    }

    private fun showLoginEmailLayout(){
        pageTag = 2
        mBinding.ivBackLogin.visibility = View.VISIBLE
        mBinding.methodContainer.visibility = View.GONE
        mBinding.phoneContainer.visibility = View.GONE
        mBinding.emailContainer.visibility = View.VISIBLE
    }

    /**
     * 设置国家/地区码
     * @param code 国家/地区码
     */
    private fun setCountryCode(code: String) {
        countryCode = code
        mBinding.tvPhoneCode.text = "+$code"
    }

    /**
     * 获取OTP
     * @param isPhone 手机号
     */
    private fun getOTPAction(isPhone :Boolean,accountStr: String){
        val phoneStr :String = if (isPhone) accountStr else ""
        val countryCode :String = if (isPhone) countryCode else ""
        val email: String = if (isPhone) "" else accountStr
        if ((!StrUtil.isEmpty(countryCode) && !StrUtil.isEmpty(phoneStr)) || !StrUtil.isEmpty(email)){
            if (isPhone) {
                mViewModel.getOTPCode(countryCode, phoneStr, "login")
            }
        }
    }


    /*********************************************Google*****************************************/

    private fun initGoogleLogin(){
        credentialManager = CredentialManager.create(this)
        val signInWithGoogleOption: GetSignInWithGoogleOption = GetSignInWithGoogleOption.Builder("461172452242-ggohvbsg2j3dd95n4bm3it0t2bg6elrh.apps.googleusercontent.com").build()
        mGoogleRequest = GetCredentialRequest.Builder()
            .addCredentialOption(signInWithGoogleOption)
            .build()
    }

    /**Google 登录*/
    private fun checkGoogleLogin(){
        scope.launch {
            credentialManager?.let { mg->
                try {
                    val result = mg.getCredential(this@LoginActivity, mGoogleRequest!!)
                    handleSignInResult(result)
                }catch (e: Exception){
                    LogUtil.e("---"+e.message)
                }
            }
        }
    }

    /**处理Google 登录结果*/
    private fun handleSignInResult(result: GetCredentialResponse){
        when(val credential = result.credential){
            is CustomCredential -> {
                if (credential.type == GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL){
                    try {
                        val googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.data)
                        //LogUtil.i("--Account: "+googleIdTokenCredential.idToken)
                        var accountId = JwtParserUtil.parseIdToken(googleIdTokenCredential.idToken)
                        if (StrUtil.isEmpty(accountId))
                            accountId = googleIdTokenCredential.id
                        val emailTx: String = if (googleIdTokenCredential.id.contains("gmail.com")) googleIdTokenCredential.id else ""
                        mHandler.post {
                            showLoadingDialog("")
                            typeTag = 3
                            // TODO: Google登录功能需要新的API接口支持
                            // mViewModel.loginAccount(
                            //     AccountLoginReq(code = null, phone = null, email = emailTx, msgCode = null,
                            //         loginMsg = accountId, loginType = 2, source = 1
                            //     )
                            // )
                        }
                    } catch (e: GoogleIdTokenParsingException) {
                        toastShow("Received an invalid google id token response")
                        LogUtil.e("Received an invalid google id token response", e)
                    }
                }else {
                    toastShow("Unexpected type of credential")
                    LogUtil.i("--Account EX: Unexpected type of credential 2")
                }
            }
            else -> {
                toastShow("Unexpected type of credential")
                LogUtil.i("--Account EX: Unexpected type of credential")
            }
        }
    }

    /*****************************************TouchId*************************************/

    // 指纹登录相关方法已注释
    /*
    private fun setBiometricLayout(){
        val isEnableBio = BiometricManager.from(applicationContext).canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) == BiometricManager.BIOMETRIC_SUCCESS
        mBinding.ivTouchId.visibility = if (isEnableBio) View.VISIBLE else View.GONE
        if (!isEnableBio)
            return
        //判断指纹加密缓存,不一定跟当前账号挂钩
        wrapperCache = bioHelper.getCipherTextWrapper(applicationContext)
        mBinding.ivTouchId.visibility = if (wrapperCache!=null) View.VISIBLE else View.GONE
    }
    */

    /**
     * 显示指纹认证弹框
     */
    private fun showBiometricAuth(){
        if (null == wrapperCache)
            return
        val cipher: Cipher? = bioHelper.getInitCipherForDecryption(CryptographyHelper.BIOMETRIC_KEY, wrapperCache!!.initVector)
        if (cipher == null) {
            toastShow("TouchId Data Error!")
            return
        }
        val prompt: BiometricPrompt = BiometricPopUtil.createBiometricPrompt(this, object : IBiometricPopListener {

            override fun onAuthSuccess(result: BiometricPrompt.AuthenticationResult) {
                if (null != result.cryptoObject && null != result.cryptoObject!!.cipher) {
                    try {
                        val cipherData = result.cryptoObject!!.cipher
                        val plaintext = bioHelper.decryptData(wrapperCache!!.ciphertext, cipherData!!)
                        LogUtil.i("---Touch id decrypt = $plaintext")
                        if (plaintext == DataCode.TOUCH_ID_KEY){
                            DataAppManager.instance.lastFingerprintToken()?.let { tokenL->
                                showLoadingDialog("")
                                typeTag = 4
                                mViewModel.loginAccountToken(tokenL)
                            }
                        }
                    }catch (e :Exception){
                        e.printStackTrace()
                        toastShow("TouchId Data Error!")
                    }
                } else {
                    toastShow("TouchId Data Error!")
                }
            }

            override fun onAuthFailed(reason: String?) {
                if (!StrUtil.isEmpty(reason))
                    toastShow(reason)
            }
        })
        val promptInfo: BiometricPrompt.PromptInfo = BiometricPopUtil.createPromptInfo(this)
        prompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))
    }

    //-----------------------------------------------------------------------------------

    private var exitTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - exitTime < 1000L) {
                finishAffinity(); // 结束这个应用的所有Activity
            } else {
                if (pageTag!=0){
                    setMethodLayout()
                }else{
                    exitTime = System.currentTimeMillis()
                }
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    /**
     * 获取协议语言参数
     * 规则：中文(zh) -> cn，其他语言 -> vi（默认）
     */
    private fun getAgreementLangParam(): String {
        val languageCode = LanguageConfig.instance.getLanguageCode()
        return if (languageCode == Language.ZH) "cn" else "vi"
    }

}